<!DOCTYPE html>
<html lang="zh-CN,en,zh-HK,zh-TW,default">
<head hexo-theme='https://github.com/volantis-x/hexo-theme-volantis/tree/4.0.0'>
  <meta charset="utf-8">
  <!-- SEO相关 -->
  
    
  
  <!-- 渲染优化 -->
  <meta name="renderer" content="webkit">
  <meta name="force-rendering" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
  <meta name="HandheldFriendly" content="True" >
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta http-equiv='x-dns-prefetch-control' content='on' />

  <!-- 页面元数据 -->
  
  <title>keras深度学习手写数字、猫狗、石头剪刀布识别 - HardyDragon Index</title>
  
    <meta name="keywords" content="CNN,mnist手写数字识别,猫狗二分类,石头剪刀布三分类,keras">
  

  

  <!-- feed -->
  

  <!-- import meta -->
  
    
      <meta name="msapplication-TileColor" content="#ffffff">
    
      <meta name="msapplication-config" content="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/browserconfig.xml">
    
      <meta name="theme-color" content="#ffffff">
    
  

  <!-- link -->
  <link rel='dns-prefetch' href='https://cdn.jsdelivr.net'>
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.14/css/all.min.css">

  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/l-lin/font-awesome-animation/dist/font-awesome-animation.min.css">

  

  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.css">

  

  

  
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.css">
  

  

  <!-- import link -->
  
  
  <link rel="apple-touch-icon" sizes="180x180" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/apple-touch-icon.png">
  <link rel="icon" type="image/png" sizes="32x32" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  <link rel="icon" type="image/png" sizes="16x16" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  <link rel="manifest" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/site.webmanifest">
  <link rel="mask-icon" href="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/blog/favicon/safari-pinned-tab.svg" color="#5bbad5">
  <link rel="shortcut icon" href="https://s1.ax1x.com/2020/10/02/0l3pPe.png">
  

  
    
      
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@9.18.1/styles/solarized-light.css">

    
  
  
    
<link rel="stylesheet" href="/blog/css/style.css">

  
  
  
  <!-- 脚本懒加载函数 -->
  <script>
  function loadScript(src, cb) {
    var HEAD = document.getElementsByTagName('head')[0] || document.documentElement;
    var script = document.createElement('script');
    script.setAttribute('type','text/javascript');
    if (cb) script.onload = cb;
    script.setAttribute('src', src);
    HEAD.appendChild(script);
  }
  //https://github.com/filamentgroup/loadCSS
  !function(c){"use strict";var e=function(e,t,n,r){var o,i=c.document,a=i.createElement("link");if(t)o=t;else{var d=(i.body||i.getElementsByTagName("head")[0]).childNodes;o=d[d.length-1]}var f=i.styleSheets;if(r)for(var l in r)r.hasOwnProperty(l)&&a.setAttribute(l,r[l]);a.rel="stylesheet",a.href=e,a.media="only x",function e(t){if(i.body)return t();setTimeout(function(){e(t)})}(function(){o.parentNode.insertBefore(a,t?o:o.nextSibling)});var s=function(e){for(var t=a.href,n=f.length;n--;)if(f[n].href===t)return e();setTimeout(function(){s(e)})};function u(){a.addEventListener&&a.removeEventListener("load",u),a.media=n||"all"}return a.addEventListener&&a.addEventListener("load",u),(a.onloadcssdefined=s)(u),a};"undefined"!=typeof exports?exports.loadCSS=e:c.loadCSS=e}("undefined"!=typeof global?global:this);
  </script>
  <script id="loadcss"></script>
</head>

<body>
  <header class="l_header always shadow blur "  >
  <div class='container'>
  <div class='wrapper'>
    <div class='nav-sub'>
      <p class="title"></p>
      <ul class='switcher nav-list-h m-phone' id="pjax-header-nav-list">
        <li><a class="s-comment fas fa-comments fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
          <li><a class="s-toc fas fa-list fa-fw" target="_self" href='javascript:void(0)'></a></li>
        
      </ul>
    </div>
		<div class="nav-main">
      
        
        <a class="title flat-box" target="_self" href='/blog/'>
          
          
            <i class='https://s1.ax1x.com/2020/10/02/0l3pPe.png'></i>
          
          
            HardyDragon
          
        </a>
      

			<div class='menu navigation'>
				<ul class='nav-list-h m-pc'>
          
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/
                  
                  
                  
                    id="blog"
                  >
                  <i class='fas fa-rss fa-fw'></i>博客
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/categories/
                  
                  
                  
                    id="blogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/tags/
                  
                  
                  
                    id="blogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/friends/
                  
                  
                  
                    id="blogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/about/
                  
                  
                  
                    id="blogabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://blog.csdn.net/qq_44880154
                  
                  
                  
                    id="https:blogcsdnnetqq_44880154"
                  >
                  <i class='fas fa-fire fa-fw'></i>CSDN
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://gitee.com/hardychenlong
                  
                  
                  
                    id="https:giteecomhardychenlong"
                  >
                  <i class='fas fa-clock fa-fw'></i>gitee
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
            
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantis"
                  >
                  主题源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/releases/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisreleases"
                  >
                  更新日志
                </a>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  有疑问？
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/faqs/
                  
                  
                  
                    id="blogfaqs"
                  >
                  看 FAQ
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/volantis-docs/
                  
                  
                  
                    id="https:githubcomvolantis-xvolantis-docs"
                  >
                  看 本站源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/issues/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisissues"
                  >
                  提 Issue
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  公告和测试博文
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/examples/
                  
                  
                  
                    id="blogexamples"
                  >
                  示例博客
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/contributors/
                  
                  
                  
                    id="blogcontributors"
                  >
                  特别感谢
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
          
				</ul>
			</div>

      <div class="m_search">
        <form name="searchform" class="form u-search-form">
          <i class="icon fas fa-search fa-fw"></i>
          <input type="text" class="input u-search-input" placeholder="搜索" />
        </form>
      </div>

			<ul class='switcher nav-list-h m-phone'>
				
					<li><a class="s-search fas fa-search fa-fw" target="_self" href='javascript:void(0)'></a></li>
				
				<li>
          <a class="s-menu fas fa-bars fa-fw" target="_self" href='javascript:void(0)'></a>
          <ul class="menu-phone list-v navigation white-box">
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/
                  
                  
                  
                    id="blog"
                  >
                  <i class='fas fa-rss fa-fw'></i>博客
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/categories/
                  
                  
                  
                    id="blogcategories"
                  >
                  <i class='fas fa-folder-open fa-fw'></i>分类
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/tags/
                  
                  
                  
                    id="blogtags"
                  >
                  <i class='fas fa-tags fa-fw'></i>标签
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  <i class='fas fa-archive fa-fw'></i>归档
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/friends/
                  
                  
                  
                    id="blogfriends"
                  >
                  <i class='fas fa-link fa-fw'></i>友链
                </a>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/about/
                  
                  
                  
                    id="blogabout"
                  >
                  <i class='fas fa-info-circle fa-fw'></i>关于
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://blog.csdn.net/qq_44880154
                  
                  
                  
                    id="https:blogcsdnnetqq_44880154"
                  >
                  <i class='fas fa-fire fa-fw'></i>CSDN
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://gitee.com/hardychenlong
                  
                  
                  
                    id="https:giteecomhardychenlong"
                  >
                  <i class='fas fa-clock fa-fw'></i>gitee
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
              
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  <i class='fas fa-ellipsis-v fa-fw'></i>更多
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantis"
                  >
                  主题源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/releases/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisreleases"
                  >
                  更新日志
                </a>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" 
                  
                  
                  >
                  有疑问？
                </a>
                
                  <ul class="list-v">
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/faqs/
                  
                  
                  
                    id="blogfaqs"
                  >
                  看 FAQ
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/volantis-docs/
                  
                  
                  
                    id="https:githubcomvolantis-xvolantis-docs"
                  >
                  看 本站源码
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=https://github.com/volantis-x/hexo-theme-volantis/issues/
                  
                  
                  
                    id="https:githubcomvolantis-xhexo-theme-volantisissues"
                  >
                  提 Issue
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
                    
                      
            
              <hr>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/archives/
                  
                  
                  
                    id="blogarchives"
                  >
                  公告和测试博文
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/examples/
                  
                  
                  
                    id="blogexamples"
                  >
                  示例博客
                </a>
                
              </li>
            
          
                    
                      
            
              <li>
                <a class="menuitem flat-box faa-parent animated-hover" href=/blog/contributors/
                  
                  
                  
                    id="blogcontributors"
                  >
                  特别感谢
                </a>
                
              </li>
            
          
                    
                  </ul>
                
              </li>
            
          
            
          </ul>
        </li>
			</ul>
		</div>
	</div>
  </div>
</header>

  <div class="l_body">
    <div class="l_cover">
  
    
    
        <div class='cover-wrapper post dock' style="display: none;">
          
            <div class='cover-backstretch'></div>
          
          <div class='cover-body'>
  <div class='top'>
    
    
      <p class="title">HardyDragon</p>
    
    
  </div>
  <div class='bottom'>
    <div class='menu navigation'>
      <div class='list-h'>
        
          
            <a target="_blank" rel="noopener" href="https://gitee.com/hardychenlong"
              
              
              id="https:giteecomhardychenlong">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f5c3.svg'><p>Gitee</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_44880154"
              
              
              id="https:blogcsdnnetqq_44880154">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f516.svg'><p>CSDN</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://volantis.js.org/examples/"
              
              
              id="https:volantisjsorgexamples">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f396.svg'><p>示例</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://volantis.js.org/examples/"
              
              
              id="https:volantisjsorgexamples">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f389.svg'><p>社区</p>
            </a>
          
            <a href="/blog/archives/"
              
              
              id="blogarchives">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f4f0.svg'><p>博客</p>
            </a>
          
            <a target="_blank" rel="noopener" href="https://github.com/volantis-x/hexo-theme-volantis/"
              
              
              id="https:githubcomvolantis-xhexo-theme-volantis">
              <img src='https://cdn.jsdelivr.net/gh/twitter/twemoji@13.0/assets/svg/1f9ec.svg'><p>源码</p>
            </a>
          
        
      </div>
    </div>
  </div>
</div>

          <div class="scroll-down" style="display: none;"><i class="fa fa-chevron-down scroll-down-effects"></i></div>
        </div>
    
  
  </div>
  
    <div class='safearea'>
      <div class='body-wrapper' id="pjax-container">
        
          <!--此文件用来存放一些不方便取值的变量--> 
<!--思路大概是将值藏到重加载的区域内--> 
 
 
 
<div id="pjax-data" style="display: none"> 
  <div id="pjax-ispage">true</div> 
  <div id="pjax-pageTitle">keras深度学习手写数字、猫狗、石头剪刀布识别</div> 
  <div id="pjax-enable-cover">true</div> 
  <div id="pjax-comment-path"></div> 
  <div id="pjax-comment-placeholder"></div> 
</div> 
 
 
<script> 
  // 处理封面 此时 jquery 还没加载 
  if ("none" == "none") { // 移除封面 
    document.getElementsByClassName('cover-wrapper')[0].style.display = "none"; 
    document.getElementsByClassName('l_header', 'cover-wrapper')[0].classList.add("show"); 
  } else { 
    if ("none" == "half") { // 半屏 
      document.getElementsByClassName('cover-wrapper')[0].setAttribute('id', 'half'); 
      document.getElementsByClassName('scroll-down')[0].style.display = "none"; 
    } else if ("none" == "full") { // 全屏 
      document.getElementsByClassName('cover-wrapper')[0].setAttribute('id', 'full'); 
      document.getElementsByClassName('scroll-down')[0].style.display = ""; 
    } 
    document.getElementsByClassName('cover-wrapper')[0].style.display = ""; 
    document.getElementsByClassName('l_header', 'cover-wrapper')[0].classList.remove("show"); 
  } 
</script> 
 

        
        

<div class='l_main'>
  <article class="article post white-box reveal md shadow article-type-post" id="post" itemscope itemprop="blogPost">
  


  
  <div class="article-meta" id="top">
    
    
    
      <h1 class="title">
        keras深度学习手写数字、猫狗、石头剪刀布识别
      </h1>
      <div class='new-meta-box'>
        
          
            
<div class='new-meta-item author'>
  <a class='author' href="/" rel="nofollow">
    <img no-lazy src="">
    <p>请设置文章作者</p>
  </a>
</div>

          
        
          
            

          
        
          
            <div class="new-meta-item date">
  <a class='notlink'>
    <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
    <p>发布于：2020年11月1日</p>
  </a>
</div>

          
        
          
            
  <div class="new-meta-item browse leancloud">
    <a class='notlink'>
      
      <div id="lc-pv" data-title="keras深度学习手写数字、猫狗、石头剪刀布识别" data-path="/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/">
        <i class="fas fa-eye fa-fw" aria-hidden="true"></i>
        <span id='number'><i class="fas fa-circle-notch fa-spin fa-fw" aria-hidden="true"></i></span>
        次浏览
      </div>
    </a>
  </div>


          
        
      </div>
    
  </div>


  
  <h1 id="使用keras搭建简单的CNN网络训练流程："><a href="#使用keras搭建简单的CNN网络训练流程：" class="headerlink" title="使用keras搭建简单的CNN网络训练流程："></a>使用keras搭建简单的CNN网络训练流程：</h1><ol>
<li><a href="#1">数据预处理，生成x、y训练集np数组</a></li>
<li><a href="#2">搭建神经网络 Sequential()</a></li>
<li><a href="#3">compile 配置训练参数</a></li>
<li><a href="#4">将x、y数组扔去网络里 fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数</a></li>
<li><a href="#5">保存模型</a></li>
<li><a href="#6">使用模型识别测试图片</a></li>
</ol>
<p>+++</p>
<h2 id="1-数据预处理，生成x、y训练集np数组"><a href="#1-数据预处理，生成x、y训练集np数组" class="headerlink" title="1.数据预处理，生成x、y训练集np数组"></a><a name="1">1.数据预处理，生成x、y训练集np数组</a></h2><p>以图片分类为例，对于数据预处理的目的就是为了得到每个图片的数据并将其封装为<strong>x数组</strong>，将图片对应的分类封装为<strong>y数组</strong>。因为后期要用这两个数组输入进神经网络，所以要生成指定要求的数组，这方面要求十分严格，如果<strong>x数组</strong>与神经网络的第一层要求的输入大小不匹配，就无法进行训练。其中需要注意的是x、y数组之间的关系，y中的每一个元素是x数组中每一个图片的分类结果，这就意味着我们是用已知的、已经分好类的数据来训练<strong>即监督学习</strong>，我们希望通过监督学习来让程序可以举一反三识别其他的图片并给出指定的分类结果。</p>
<p>有时候训练集的x、y数组已经被封装好了，例如mnist，只需要调用对应函数即可获得两个数组，但是对于没有封装的情况，则需要自己对图片打上标签封装好x、y数组。其具体思路可以在以下关于剪刀石头布的数据预处理中体现：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># paper:0;  rock:1;  scissors:2</span></span><br><span class="line">x_train = []</span><br><span class="line">y_train = []</span><br><span class="line"><span class="keyword">for</span> subfloder <span class="keyword">in</span> os.listdir(<span class="string">&#x27;rps/&#x27;</span>):</span><br><span class="line">    <span class="keyword">for</span> picname <span class="keyword">in</span> os.listdir(<span class="string">&#x27;rps/&#x27;</span> + subfloder):</span><br><span class="line">        img = np.array(load_img(<span class="string">&#x27;rps/&#x27;</span> + subfloder + <span class="string">&#x27;/&#x27;</span> + picname, target_size=(<span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)))</span><br><span class="line">        img = img / <span class="number">255.0</span></span><br><span class="line">        x_train.append(img)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">&#x27;paper&#x27;</span> <span class="keyword">in</span> picname:</span><br><span class="line">            y_train.append(<span class="number">0</span>)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">&#x27;rock&#x27;</span> <span class="keyword">in</span> picname:</span><br><span class="line">            y_train.append(<span class="number">1</span>)</span><br><span class="line">        <span class="keyword">if</span> <span class="string">&#x27;scissors&#x27;</span> <span class="keyword">in</span> picname:</span><br><span class="line">            y_train.append(<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line">x_train = np.array(x_train)</span><br><span class="line">y_train = to_categorical(y_train, <span class="number">3</span>)</span><br><span class="line">y_train = np.array(y_train)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 新加 为了消除过拟合：打乱训练集的样本和标签；</span></span><br><span class="line">np.random.seed(<span class="number">200</span>)</span><br><span class="line">np.random.shuffle(x_train)</span><br><span class="line">np.random.seed(<span class="number">200</span>)</span><br><span class="line">np.random.shuffle(y_train)</span><br></pre></td></tr></table></figure>

<p>其中给到我们的可能是3个分别放有剪刀、石头、布的图片文件夹，里面的图片可能命名是乱七八糟的，就像是从网上爬取下来的随便命名的，也可能是已经有对应的关键字处理过的，可以通过文件名来判断其分类的。如果遇到前者这需要对各个文件夹下的图片重命名给其加上对应的关键字，这样方便之后对y数组填充数据，通过关键词判断这个图片对于的分类是什么。如果是后者便无需重命名，如上面的代码，其图片的结构大致如下：</p>
<p><img src="https://gitee.com/hardychenlong/giteeblogimg/raw/master/20201101152728.png" class="lazyload" data-srcset="https://gitee.com/hardychenlong/giteeblogimg/raw/master/20201101152728.png" srcset="" alt="image-20201101152721793"></p>
<p>之后需要将x列表、y列表（一开始先初始化x、y数组为python的列表）转换为np数组，因为神经网络只接受np数组输入，这也是十分严格的。其中对于y列表的处理方法有些不一样，需要先利用keras.utils 下的 to_categorical() 函数对其进行自动分类，这会让y数组每一个元素的长度及内容发生改变，由原本列表元素是0、1、2组成的变为每个元素是一个长度为分类个数的数组，并在对应的下标分类上的值为<strong>1</strong>其余为<strong>0</strong> ，其第二个参数便是分类的个数（即确定数组的元素长度），剪刀石头布显然是三分类，如果是猫狗识别便是二分类需要填入2。至于为何要如此，理由大概是因为神经网络严格要求的，非要对y数组进行 to_categorical() 处理，才被允许输入。</p>
<p>可以稍微看看生成后的x数组、y数组长什么样，看看他们的形状以及(打乱后的)y标签的前10个标签。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">print(x_train.shape)</span><br><span class="line">print(y_train.shape)</span><br><span class="line">print(y_train[:<span class="number">10</span>])</span><br></pre></td></tr></table></figure>

<p>result：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">(2520, 100, 100, 3)</span><br><span class="line">(2520, 3)</span><br><span class="line">[[0. 1. 0.]</span><br><span class="line"> [0. 1. 0.]</span><br><span class="line"> [0. 0. 1.]</span><br><span class="line"> [0. 0. 1.]</span><br><span class="line"> [0. 0. 1.]</span><br><span class="line"> [1. 0. 0.]</span><br><span class="line"> [1. 0. 0.]</span><br><span class="line"> [0. 0. 1.]</span><br><span class="line"> [0. 0. 1.]</span><br><span class="line"> [0. 1. 0.]]</span><br></pre></td></tr></table></figure>

<p>为什么不看x数组呢，因为其数组内的每个元素就是一张图片上的所有像素点的np数组（且做了归一化处理 即除于 255.0 便于减少CPU的浮点数运算量），不便显示。</p>
<p>接下来继续深入了解关于x数组如何将图片变成像素点然后放入数组的细节，利用 os 库的 listdir() 函数 【参数是文件目录】遍历目录下的所有文件（图片），利用 keras.preprocessing.image 库的 load_img() 函数读取图片【load_img 参数为 <strong>图片路径</strong> ，其中target_size 参数是读入图片时的大小，这是个重点，因为要和神经网络第一层的输入匹配。】，同时将载入的图片利用 np_array() 转换为np数组。接着对np数组<strong>除以 255.0</strong> (255 也行，这是归一化处理，将像素点缩小数值便于运算) ，这是x数组的部分结果，还是拿出来看看吧。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[[[0.99607843 0.99607843 0.99607843]</span><br><span class="line">  [0.99607843 0.99607843 0.99607843]</span><br><span class="line">  [0.99607843 0.99607843 0.99607843]</span><br><span class="line">  ...</span><br></pre></td></tr></table></figure>

<p> 经过以上的处理后我们便得到x数组和y数组了，便有了数据可以输入神经网络，但是值得注意的是我们自己制作的训练集（即x、y数组）和已经封装好的训练集例如mnist还是有些不一样的，我们自己封装的数据集没有经过打乱，全部都是安装文件夹读取顺序来的，所以会看到y数组的一开始的元素全是一模一样，然后这会导致我们训练过程中的验证准确度异常，至于为何，可能是训练时使用了数据集分隔参数，使得各分类样本不均匀导致过拟合，所以我们利用 numpy.random 中的 shuffle() 函数对x数组和y数组打乱，但是打乱顺序要一样，不然x数组的图片就匹配不上y数组的分类结果了，所以需要在每次打乱之前设置一个种子seed()传入一个整数，使得随机可复现，对训练集的数据打乱后也可以在训练的时候fit 添加一个shuffle=True 的参数使其将数据集随机输入，使得样本更加随机。</p>
<h2 id="2-搭建神经网络-Sequential"><a href="#2-搭建神经网络-Sequential" class="headerlink" title="2.搭建神经网络 Sequential()"></a><a name="2">2.搭建神经网络 Sequential()</a></h2><p>在有了训练集数据后，接下来搭建简单的CNN卷积神经网络利用已分类好的图片对模型进行训练：</p>
<ol>
<li>首先利用 keras.models 库 初始化一个线性的网络结构 Sequential() </li>
<li>第一层输入层以卷积作为输入层，需要指定输入的数组形状 input_shape，卷积核数目 filters，卷积核大小 kernel_size ，注意输入的数组形状要和x训练集数组的各个元素大小一致。其中核数目和大小决定了训练的速度和效果，核数目多便慢但采集的细节更多，核大小越大采集的细节相对少。</li>
<li>输入层后便是卷积池化层，卷积层和池化层是配对出现的，有卷积就有池化，它们的写法也比较固定：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">model.add(Conv2D(filters=<span class="number">16</span>, activation=<span class="string">&#x27;relu&#x27;</span>, kernel_size=<span class="number">3</span>, strides=<span class="number">2</span>))</span><br><span class="line">model.add(MaxPool2D(pool_size=<span class="number">2</span>))</span><br></pre></td></tr></table></figure>

<p>卷积层需要指定核数目 filters 激活函数 activation 一般是 <strong>relu</strong> 核大小 kernel_size，步长 strides (卷积核每次卷积时的移动长度)，或者padding 填充方式。</p>
<p>池化层可以只指定核大小 pool_size ，2 代表的就是(2,2) 即2*2大小的小正方形，或者步长strides。</p>
<ol start="4">
<li>卷积池化，一般3层，其核数目有一定规律：16、32、64，可以不设置步长，便训练的慢些，激活函数relu稳定效果较好</li>
<li>卷积池化后输入后便是扁平层 Flatten() 即将多维数组全部变为一维的。</li>
<li>降维打击后进入全连接层 Dense，全连接层只能接受一维的数组所以必须对其降维，需要的第一个参数为输出的结果数目 ，一般是512，然后指定激活函数，如果不是作为最后输出层的全连接层一般激活函数为relu。一般除了输出层外只有一个全连接层。</li>
<li>全连接层后可以跟着一个Dropout 随机丢弃一些数据达到更好的效果，参数为一个小数，作为丢弃数据的比例。</li>
<li>最后的全连接输出层，这是一个重点，需要指定输出的结果个数和分类的个数相同，例如三分类就是第一个参数为3，输入3个节点，对应三个分类，其中值为1或者值较高的那个节点就是输出的分类，对于多分类使用的激活函数为 softmax ，二分类使用 激活函数sigmoid 且其输出结果为1：</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">model.add(Dense(<span class="number">1</span>, activation=<span class="string">&#x27;sigmoid&#x27;</span>))</span><br><span class="line">model.add(Dense(<span class="number">3</span>, activation=<span class="string">&#x27;softmax&#x27;</span>))</span><br></pre></td></tr></table></figure>

<p>通用的CNN简单分类网络，多分类，二分类：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 多分类</span></span><br><span class="line">model = Sequential()</span><br><span class="line">model.add(Conv2D(input_shape=(<span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>), filters=<span class="number">16</span>, kernel_size=<span class="number">3</span>))</span><br><span class="line">model.add(Conv2D(filters=<span class="number">16</span>, activation=<span class="string">&#x27;relu&#x27;</span>, kernel_size=<span class="number">3</span>, strides=<span class="number">2</span>))</span><br><span class="line">model.add(MaxPool2D(pool_size=<span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Conv2D(filters=<span class="number">32</span>, activation=<span class="string">&#x27;relu&#x27;</span>, kernel_size=<span class="number">3</span>))</span><br><span class="line">model.add(MaxPool2D(pool_size=<span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Conv2D(filters=<span class="number">64</span>, activation=<span class="string">&#x27;relu&#x27;</span>, kernel_size=<span class="number">3</span>))</span><br><span class="line">model.add(MaxPool2D(pool_size=<span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Flatten())</span><br><span class="line">model.add(Dense(<span class="number">512</span>, activation=<span class="string">&#x27;relu&#x27;</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.3</span>))</span><br><span class="line">model.add(Dense(<span class="number">3</span>, activation=<span class="string">&#x27;softmax&#x27;</span>))</span><br></pre></td></tr></table></figure>

<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 二分类</span></span><br><span class="line">model = Sequential()</span><br><span class="line">model.add(Conv2D(<span class="number">16</span>, <span class="number">3</span>, input_shape=(<span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)))</span><br><span class="line">model.add(Conv2D(<span class="number">16</span>, <span class="number">3</span>, activation=<span class="string">&#x27;relu&#x27;</span>))</span><br><span class="line">model.add(MaxPool2D(<span class="number">2</span>, <span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Conv2D(<span class="number">32</span>, <span class="number">3</span>, activation=<span class="string">&#x27;relu&#x27;</span>, padding=<span class="string">&#x27;same&#x27;</span>))</span><br><span class="line">model.add(MaxPool2D(<span class="number">2</span>, <span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Conv2D(<span class="number">64</span>, <span class="number">3</span>, activation=<span class="string">&#x27;relu&#x27;</span>, strides=<span class="number">2</span>, padding=<span class="string">&#x27;same&#x27;</span>))</span><br><span class="line">model.add(MaxPool2D(<span class="number">2</span>, <span class="number">2</span>))</span><br><span class="line"></span><br><span class="line">model.add(Flatten())</span><br><span class="line">model.add(Dense(<span class="number">512</span>, activation=<span class="string">&#x27;relu&#x27;</span>))</span><br><span class="line">model.add(Dropout(<span class="number">0.3</span>))</span><br><span class="line">model.add(Dense(<span class="number">1</span>, activation=<span class="string">&#x27;sigmoid&#x27;</span>))</span><br></pre></td></tr></table></figure>

<h2 id="3-compile-配置训练参数"><a href="#3-compile-配置训练参数" class="headerlink" title="3.compile 配置训练参数"></a><a name="3">3.compile 配置训练参数</a></h2><p>在对模型训练前需要配置一些训练时用的优化器 optimizer ，一般是SGD、Adam，然后对其学习率 lr 进行调整</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">SGD默认学习率 lr&#x3D;0.01</span><br><span class="line">Adam lr&#x3D;0.001</span><br></pre></td></tr></table></figure>

<p>配置损失函数，二分类用 binary_crossentropy 、 多分类用 categorical_crossentropy<br>训练评分标准 <strong>metrics=[‘accuracy’]</strong> </p>
<p>多分类：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">model.compile(</span><br><span class="line">    optimizer=keras.optimizers.SGD(lr=<span class="number">0.02</span>),</span><br><span class="line">    loss=keras.losses.categorical_crossentropy,</span><br><span class="line">    metrics=[<span class="string">&#x27;accuracy&#x27;</span>]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>二分类：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">model.compile(</span><br><span class="line">    optimizer=keras.optimizers.Adam(lr=<span class="number">0.0002</span>),</span><br><span class="line">    loss=keras.losses.binary_crossentropy,</span><br><span class="line">    metrics=[<span class="string">&#x27;accuracy&#x27;</span>]</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<h2 id="4-将x、y数组扔去网络里-fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数"><a href="#4-将x、y数组扔去网络里-fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数" class="headerlink" title="4.将x、y数组扔去网络里 fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数"></a><a name="4">4.将x、y数组扔去网络里 fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数</a></h2><p>使用fit() 函数传入x数组、y数组，训练周期，训练集和验证集分为 8:2 ，即validation_split = 0.2 ;<br>单次输入数据大小 batch_size,verbose 查看训练的试图方式，shuffle 默认打乱为True</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">model.fit(</span><br><span class="line">    x=x_train,</span><br><span class="line">    y=y_train,</span><br><span class="line">    epochs=<span class="number">5</span>,</span><br><span class="line">    validation_split=<span class="number">0.2</span>,</span><br><span class="line">    batch_size=<span class="number">64</span>,</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<p>如果想要再训练过后显示loss和accuracy，可以将fit 的结果赋值给一个变量，对变量调用其history去除对应的loss和acc。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">result = model.fit(x=x_train, y=y_train, epochs=<span class="number">10</span>, verbose=<span class="number">2</span>, validation_split=<span class="number">0.2</span>, batch_size=<span class="number">32</span>, shuffle=<span class="literal">True</span>)</span><br><span class="line"><span class="comment">#print(abs(float(result.history[&#x27;loss&#x27;][-1])))</span></span><br><span class="line">print(result.history[<span class="string">&#x27;loss&#x27;</span>][<span class="number">-1</span>])</span><br><span class="line">print(result.history[<span class="string">&#x27;acc&#x27;</span>][<span class="number">-1</span>])</span><br></pre></td></tr></table></figure>



<h2 id="5-保存模型"><a href="#5-保存模型" class="headerlink" title="5.保存模型"></a><a name="5">5.保存模型</a></h2><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">model.save(<span class="string">&#x27;rps_shuffle_model_cnn.h5&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>保存模型为 h5文件 到当前目录</p>
<h2 id="6-使用模型识别测试图片"><a href="#6-使用模型识别测试图片" class="headerlink" title="6.使用模型识别测试图片"></a><a name="6">6.使用模型识别测试图片</a></h2><ol>
<li><p>读取图片 load_img() </p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">load_img</span>(<span class="params">path, grayscale=False, color_mode=<span class="string">&#x27;rgb&#x27;</span>, target_size=None,</span></span></span><br><span class="line"><span class="function"><span class="params">             interpolation=<span class="string">&#x27;nearest&#x27;</span></span>):</span></span><br></pre></td></tr></table></figure>

<p>默认是 RGB 读取，即数组形状的第三个值为3，若灰度图读取第三个值为1，但是需要指定为灰度图读取。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">image = load_img(<span class="string">&#x27;mnist_test.png&#x27;</span>, color_mode=<span class="string">&#x27;grayscale&#x27;</span>, target_size=(<span class="number">28</span>, <span class="number">28</span>, <span class="number">1</span>))</span><br><span class="line">img = np.array(load_img(<span class="string">&#x27;test/27.jpg&#x27;</span>, target_size=(<span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)))</span><br></pre></td></tr></table></figure>

<p>而且读取的 target_size 需要和神经网络的输入层大小相同。</p>
</li>
<li><p>使用 matplotlib.pyplot 库的 imshow() 显示图片，需要传入图片的np数组。此时的数组维度为3维，但是输入进神经网络的维度要求是4维，所以需要<strong>升维</strong>。我们训练集的维度便是4维的np数组，所以输入其他的图片也应该是严格的要求4维，并且数据集的数据做了归一化处理，对于测试图片的np数组也是要进行归一化处理（/255）后升维。<br>升维的方式有两种：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">img = img.reshape(<span class="number">1</span>, <span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)</span><br><span class="line">image = image.reshape(<span class="number">-1</span>, <span class="number">28</span>, <span class="number">28</span>, <span class="number">1</span>)</span><br><span class="line">img = img.reshape((<span class="number">1</span>, <span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>))</span><br></pre></td></tr></table></figure>

<p>如果只是输入一张图片，那么第一个reshape()参数填1 / -1 都可以，因为-1 代表自动识别图片个数，至于参数带不带括号都行。</p>
</li>
<li><p>利用 keras.models 导入 load_model() 函数，将模型载入</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">model = load_model(<span class="string">&#x27;mnist_model_5.h5&#x27;</span>)</span><br></pre></td></tr></table></figure>

<p>将归一化并升维后的图片传入模型 使用 predict_classes() 【参数是图片的np数组】获取分类结果，返回的y数组的元素分类的下标值，可以通过一个列表和其对应配合 matplotlib.pyplot 显示分类结果和图片。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">model = load_model(<span class="string">&#x27;rps_shuffle_model_cnn_99.h5&#x27;</span>)</span><br><span class="line">result = model.predict_classes(img)</span><br><span class="line">lable = [<span class="string">&#x27;paper&#x27;</span>, <span class="string">&#x27;rock&#x27;</span>, <span class="string">&#x27;scissors&#x27;</span>]</span><br><span class="line">print(result[<span class="number">0</span>])</span><br><span class="line">plt.title(lable[result[<span class="number">0</span>]])</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>

<p><img src="https://gitee.com/hardychenlong/giteeblogimg/raw/master/20201101170155.png" class="lazyload" data-srcset="https://gitee.com/hardychenlong/giteeblogimg/raw/master/20201101170155.png" srcset="" alt="image-20201101170155591"></p>
</li>
</ol>
<p>完整的使用模型代码示例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">from</span> keras.preprocessing.image <span class="keyword">import</span> load_img</span><br><span class="line"><span class="keyword">from</span> keras.models <span class="keyword">import</span> load_model</span><br><span class="line"><span class="keyword">from</span> keras.utils <span class="keyword">import</span> to_categorical</span><br><span class="line"></span><br><span class="line"><span class="comment"># paper:0;  rock:1;  scissors:2  testpaper01-00.png testrock01-00.png testscissors01-00.png</span></span><br><span class="line">img = np.array(load_img(<span class="string">&#x27;test/testscissors01-00.png&#x27;</span>, target_size=(<span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)))</span><br><span class="line">img = img / <span class="number">255</span></span><br><span class="line">plt.imshow(img)</span><br><span class="line"></span><br><span class="line"><span class="comment"># img = img.reshape((1, 100, 100, 3))</span></span><br><span class="line"><span class="comment"># img = img.reshape(-1, 100, 100, 3)</span></span><br><span class="line">img = img.reshape(<span class="number">1</span>, <span class="number">100</span>, <span class="number">100</span>, <span class="number">3</span>)</span><br><span class="line">model = load_model(<span class="string">&#x27;rps_shuffle_model_cnn_99.h5&#x27;</span>)</span><br><span class="line">result = model.predict_classes(img)</span><br><span class="line">lable = [<span class="string">&#x27;paper&#x27;</span>, <span class="string">&#x27;rock&#x27;</span>, <span class="string">&#x27;scissors&#x27;</span>]</span><br><span class="line">print(result[<span class="number">0</span>])</span><br><span class="line">plt.title(lable[result[<span class="number">0</span>]])</span><br><span class="line">plt.show()</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>


  
  
    
    <div class='footer'>
      
      
      
        <div class='copyright'>
          <blockquote>
            
              
                <p>博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</p>

              
            
              
                <p>本文永久链接是：<a href=https://hardydragon.gitee.io/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/>https://hardydragon.gitee.io/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/</a></p>
              
            
          </blockquote>
        </div>
      
      
    </div>
  
  
    


  <div class='article-meta' id="bottom">
    <div class='new-meta-box'>
      
        
          <div class="new-meta-item date" itemprop="dateUpdated" datetime="2020-11-01T19:50:02+08:00">
  <a class='notlink'>
    <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
    <p>更新于：2020年11月1日</p>
  </a>
</div>

        
      
        
          
  
  <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/CNN/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>CNN</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/mnist%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E8%AF%86%E5%88%AB/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>mnist手写数字识别</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/%E7%8C%AB%E7%8B%97%E4%BA%8C%E5%88%86%E7%B1%BB/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>猫狗二分类</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E4%B8%89%E5%88%86%E7%B1%BB/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>石头剪刀布三分类</p></a></div> <div class="new-meta-item meta-tags"><a class="tag" href="/blog/tags/keras/" rel="nofollow"><i class="fas fa-hashtag fa-fw" aria-hidden="true"></i><p>keras</p></a></div>


        
      
        
          
  <div class="new-meta-item share -mob-share-list">
  <div class="-mob-share-list share-body">
    
      
        <a class="-mob-share-qq" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://connect.qq.com/widget/shareqq/index.html?url=https://hardydragon.gitee.io/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/&title=keras深度学习手写数字、猫狗、石头剪刀布识别 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qq.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-qzone" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="https://sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?url=https://hardydragon.gitee.io/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/&title=keras深度学习手写数字、猫狗、石头剪刀布识别 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/qzone.png" srcset="">
          
        </a>
      
    
      
        <a class="-mob-share-weibo" title="" rel="external nofollow noopener noreferrer noopener"
          
          target="_blank" href="http://service.weibo.com/share/share.php?url=https://hardydragon.gitee.io/blog/2020/11/01/%E6%B7%B1%E5%BA%A6%E5%AD%A6%E4%B9%A0%E6%89%8B%E5%86%99%E6%95%B0%E5%AD%97%E3%80%81%E7%8C%AB%E7%8B%97%E3%80%81%E7%9F%B3%E5%A4%B4%E5%89%AA%E5%88%80%E5%B8%83%E8%AF%86%E5%88%AB/&title=keras深度学习手写数字、猫狗、石头剪刀布识别 - HardyDragon Index&summary="
          
          >
          
            <img src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" class="lazyload" data-srcset="https://cdn.jsdelivr.net/gh/volantis-x/cdn-org/logo/128/weibo.png" srcset="">
          
        </a>
      
    
      
    
      
    
  </div>
</div>



        
      
    </div>
  </div>


  
  

  
    <div class="prev-next">
      
        <a class='prev' href='/blog/2021/03/22/%E7%AC%AC%E4%B8%89%E7%AB%A0%E6%95%B0%E6%8D%AE%E5%92%8CC/'>
          <p class='title'><i class="fas fa-chevron-left" aria-hidden="true"></i>第三章 数据和C</p>
          <p class='content'>第三章 数据和C3.1 示例程序3.2 变量和常量数据3.3 数据：数据类型关键字3.3.1 整数和浮点数3.3.2 整数3.3.3 浮点数3.4 C语言基本数据类型int类型其他数据类型使用其...</p>
        </a>
      
      
        <a class='next' href='/blog/2020/10/28/%E6%A0%91%E8%8E%93%E6%B4%BE%E8%B0%83%E7%94%A8%E7%99%BE%E5%BA%A6API%E5%AE%9E%E7%8E%B0%E6%9E%9C%E8%94%AC%E8%AF%86%E5%88%AB%E9%83%A8%E7%BD%B2/'>
          <p class='title'>树莓派调用百度API实现果蔬识别部署<i class="fas fa-chevron-right" aria-hidden="true"></i></p>
          <p class='content'>项目运行截图添加了一个识别按钮，将当前画面保存后调用百度的API然后返回识别的第一个最佳结果。识别结果：
即使是手机的图片识别结果也相对来说准确，但是图片有其他的太多异物可能会导致识别结果异常。...</p>
        </a>
      
    </div>
  
</article>


  

  <article class="post white-box reveal shadow" id="comments">
    <p ct><i class='fas fa-comments'></i> 评论</p>
    
    <div id="valine_container" class="valine_thread">
  <i class="fas fa-cog fa-spin fa-fw fa-2x"></i>
</div>

  </article>






</div>
<aside class='l_side'>
  
  
    
    



  <section class="widget toc-wrapper shadow desktop mobile" id="toc-div" >
    
  <header>
    
      <i class="fas fa-list fa-fw" aria-hidden="true"></i><span class='name'>本文目录</span>
    
  </header>


    <div class='content'>
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E6%95%B0%E6%8D%AE%E9%A2%84%E5%A4%84%E7%90%86%EF%BC%8C%E7%94%9F%E6%88%90x%E3%80%81y%E8%AE%AD%E7%BB%83%E9%9B%86np%E6%95%B0%E7%BB%84"><span class="toc-text">1.数据预处理，生成x、y训练集np数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E6%90%AD%E5%BB%BA%E7%A5%9E%E7%BB%8F%E7%BD%91%E7%BB%9C-Sequential"><span class="toc-text">2.搭建神经网络 Sequential()</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-compile-%E9%85%8D%E7%BD%AE%E8%AE%AD%E7%BB%83%E5%8F%82%E6%95%B0"><span class="toc-text">3.compile 配置训练参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E5%B0%86x%E3%80%81y%E6%95%B0%E7%BB%84%E6%89%94%E5%8E%BB%E7%BD%91%E7%BB%9C%E9%87%8C-fit%E8%AE%AD%E7%BB%83%EF%BC%8C%E6%8C%87%E5%AE%9A%E8%AE%AD%E7%BB%83%E9%9B%86%E5%92%8C%E9%AA%8C%E8%AF%81%E9%9B%86%E5%8F%82%E6%95%B0%E3%80%81%E8%AE%AD%E7%BB%83%E5%91%A8%E6%9C%9F%EF%BC%8C%E6%AF%8F%E6%AC%A1%E8%BD%BD%E5%85%A5%E6%95%B0%E6%8D%AE%E5%A4%A7%E5%B0%8F%E7%AD%89%E5%8F%82%E6%95%B0"><span class="toc-text">4.将x、y数组扔去网络里 fit训练，指定训练集和验证集参数、训练周期，每次载入数据大小等参数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-%E4%BF%9D%E5%AD%98%E6%A8%A1%E5%9E%8B"><span class="toc-text">5.保存模型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E4%BD%BF%E7%94%A8%E6%A8%A1%E5%9E%8B%E8%AF%86%E5%88%AB%E6%B5%8B%E8%AF%95%E5%9B%BE%E7%89%87"><span class="toc-text">6.使用模型识别测试图片</span></a></li></ol>
    </div>
  </section>


  


</aside>



        
      </div>
      
  
  <footer class="footer clearfix">
    <br><br>
    
      
        <div class="aplayer-container">
          

  
    <meting-js
      theme='#1BCDFC'
      autoplay='false'
      volume='0.7'
      loop='all'
      order='list'
      fixed='true'
      list-max-height='320px'
      server='netease'
      type='playlist'
      id='3175833810'
      list-folded='true'>
    </meting-js>
  


        </div>
      
    
      
        <br>
        <div class="social-wrapper">
          
            
          
            
          
            
              <a href="https://gitee.com/hardychenlong"
                class="social fab fa-gitee flat-btn"
                target="_blank"
                rel="external nofollow noopener noreferrer">
                
              </a>
            
          
            
          
        </div>
      
    
      
        <div><p>博客内容遵循 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议</a></p>
</div>
      
    
      
        本站使用
        <a href="https://github.com/volantis-x/hexo-theme-volantis/tree/4.0.0" target="_blank" class="codename">Volantis</a>
        作为主题
      
    
      
        <div class='copyright'>
        <p><a target="_blank" rel="noopener" href="https://hardydragon.io/">Copyright © 2020-2021 HardyDragon</a></p>

        </div>
      
    
  </footer>


      <a class="s-top fas fa-arrow-up fa-fw" href='javascript:void(0)'></a>
    </div>
  </div>
  <div>
    <!-- required -->

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5/dist/jquery.min.js"></script>

<script>
  function pjax_fancybox() {
    $(".md .gallery").find("img").each(function () { //渲染 fancybox
      var element = document.createElement("a"); // a 标签
      $(element).attr("class", "fancybox");
      $(element).attr("pjax-fancybox", "");  // 过滤 pjax
      $(element).attr("href", $(this).attr("src"));
      if ($(this).attr("data-original")) {
        $(element).attr("href", $(this).attr("data-original"));
      }
      $(element).attr("data-fancybox", "images");
      var caption = "";   // 描述信息
      if ($(this).attr('alt')) {  // 判断当前页面是否存在描述信息
        $(element).attr('data-caption', $(this).attr('alt'));
        caption = $(this).attr('alt');
      }
      var div = document.createElement("div");
      $(div).addClass("fancybox");
      $(this).wrap(div); // 最外层套 div ，其实主要作用还是 class 样式
      var span = document.createElement("span");
      $(span).addClass("image-caption");
      $(span).text(caption); // 加描述
      $(this).after(span);  // 再套一层描述
      $(this).wrap(element);  // 最后套 a 标签
    })
    $(".md .gallery").find("img").fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: false,
      closeClick: true,
      helpers: {
        overlay: {closeClick: true}
      },
      buttons: [
        "zoom",
        "close"
      ]
    });
  };
  function SCload_fancybox() {
    if ($(".md .gallery").find("img").length == 0) return;
    loadCSS("https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.css", document.getElementById("loadcss"));
    setTimeout(function() {
      loadScript('https://cdn.jsdelivr.net/gh/fancyapps/fancybox@3.5.7/dist/jquery.fancybox.min.js', pjax_fancybox)
    }, 1);
  };
  $(function () {
    SCload_fancybox();
  });
</script>


<!-- internal -->

  
  
  
    
<script src="https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js"></script>

    <script type="text/javascript">
      $(function(){
        var imgs=["https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/001.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/002.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/003.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/004.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/005.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/006.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/012.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/016.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/019.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/025.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/033.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/034.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/035.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/038.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/039.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/042.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/046.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/051.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/052.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/054.jpg", "https://cdn.jsdelivr.net/gh/volantis-x/cdn-wallpaper-minimalist/2020/056.jpg"];
        if ('true' == 'true') {
          function shuffle(arr){
            /*From countercurrent-time*/
            var n = arr.length;
            while(n--) {
              var index = Math.floor(Math.random() * n);
              var temp = arr[index];
              arr[index] = arr[n];
              arr[n] = temp;
            }
          }
          shuffle(imgs);
        }
        if ('.cover-backstretch') {
          $('.cover-backstretch').backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        } else {
          $.backstretch(
            imgs,
          {
            duration: "10000",
            fade: "1500"
          });
        }
      });
    </script>
  







  <script defer src="https://cdn.jsdelivr.net/npm/vanilla-lazyload@17.1.0/dist/lazyload.min.js"></script>
<script>
  // https://www.npmjs.com/package/vanilla-lazyload
  // Set the options globally
  // to make LazyLoad self-initialize
  window.lazyLoadOptions = {
    elements_selector: ".lazyload",
    threshold: 0
  };
  // Listen to the initialization event
  // and get the instance of LazyLoad
  window.addEventListener(
    "LazyLoad::Initialized",
    function (event) {
      window.lazyLoadInstance = event.detail.instance;
    },
    false
  );
  document.addEventListener('DOMContentLoaded', function () {
    lazyLoadInstance.update();
  });
  document.addEventListener('pjax:complete', function () {
    lazyLoadInstance.update();
  });
</script>




  
  
    <script>
      window.FPConfig = {
        delay: 0,
        ignoreKeywords: [],
        maxRPS: 5,
        hoverDelay: 25
      };
    </script>
    <script defer src="https://cdn.jsdelivr.net/gh/gijo-varghese/flying-pages@2.1.2/flying-pages.min.js"></script>
  




  <script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
    var clipboard = new ClipboardJS('.btn-copy', {
        target: function (trigger) {
            return trigger.nextElementSibling
        }
    });
    function wait(callback, seconds) {
        var timelag = null;
        timelag = window.setTimeout(callback, seconds)
    }
    function pjax_initCopyCode() {
		if($(".highlight .code pre").length+$(".article pre code").length==0)return;
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        copyHtml += '<i class="fas fa-copy"></i><span>COPY</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        $(".article pre code").before(copyHtml);
        clipboard.off('success').on('success', function (e) {
            let $btn = $(e.trigger);
            $btn.addClass('copied');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-check-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPIED';
            wait(function () {
                $icon.removeClass('fa-check-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        });
        clipboard.off('error').on('error', function (e) {
            e.clearSelection();
            let $btn = $(e.trigger);
            $btn.addClass('copy-failed');
            let $icon = $($btn.find('i'));
            $icon.removeClass('fa-copy');
            $icon.addClass('fa-times-circle');
            let $span = $($btn.find('span'));
            $span[0].innerText = 'COPY FAILED';
            wait(function () {
                $icon.removeClass('fa-times-circle');
                $icon.addClass('fa-copy');
                $span[0].innerText = 'COPY'
            }, 2000)
        })
    }
    $(function () {
        pjax_initCopyCode()
    });
</script>




   <script src="https://cdn.jsdelivr.net/npm/scrollreveal@4.0.6/dist/scrollreveal.min.js"></script>
<script type="text/javascript">
  function pjax_scrollrebeal() {
    ScrollReveal().reveal('.l_main .reveal', {
      distance: '32px',
      duration: '800',
      interval: '20',
      scale: '1',
      easing: 'ease-out'
    });
  }
  $(function () {
    pjax_scrollrebeal();
  });
</script>




  <script>
  let APlayerController = new Object();
  APlayerController.id = '3175833810';  // 设定全局音乐播放ID
  APlayerController.volume = '0.7';
</script>

  
<script src="https://cdn.jsdelivr.net/npm/aplayer@1.10/dist/APlayer.min.js"></script>


  
<script src="https://cdn.jsdelivr.net/npm/meting@2.0/dist/Meting.min.js"></script>








  
  
<script src="/blog/js/valine.js"></script>


<script>
  var GUEST_INFO = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link'.split(',').filter(function (item) {
    return GUEST_INFO.indexOf(item) > -1
  });
  var REQUIRED_FIELDS = ['nick', 'mail', 'link'];
  var requiredFields = 'nick,mail'.split(',').filter(function (item) {
    return REQUIRED_FIELDS.indexOf(item) > -1
  });

  function emoji(path, idx, ext) {
    return path + "/" + path + "-" + idx + "." + ext;
  }

  var emojiMaps = {};
  for (var i = 1; i <= 54; i++) {
    emojiMaps['tieba-' + i] = emoji('tieba', i, 'png');
  }
  for (var i = 1; i <= 101; i++) {
    emojiMaps['qq-' + i] = emoji('qq', i, 'gif');
  }
  for (var i = 1; i <= 116; i++) {
    emojiMaps['aru-' + i] = emoji('aru', i, 'gif');
  }
  for (var i = 1; i <= 125; i++) {
    emojiMaps['twemoji-' + i] = emoji('twemoji', i, 'png');
  }
  for (var i = 1; i <= 4; i++) {
    emojiMaps['weibo-' + i] = emoji('weibo', i, 'png');
  }

  function pjax_valine() {
    if(!document.querySelectorAll("#valine_container")[0])return;

    let pagePlaceholder = $.trim($('#pjax-comment-placeholder').text()) || "快来评论吧~";

    let path = $.trim($('#pjax-comment-path').text());
    if (path.length == 0) {
      let defaultPath = '';
      path = defaultPath || decodeURI(window.location.pathname);
    }

    var valine = new Valine();
    valine.init({
      el: '#valine_container',
      meta: meta,
      placeholder: pagePlaceholder,
      path: path,
      appId: "",
      appKey: "",
      pageSize: '10',
      avatar: 'robohash',
      lang: 'zh-cn',
      visitor: 'true',
      highlight: 'true',
      mathJax: 'false',
      enableQQ: 'true',
      recordIP: false,
      requiredFields: requiredFields,
      emojiCDN: 'https://cdn.jsdelivr.net/gh/volantis-x/cdn-emoji/valine/',
      emojiMaps: emojiMaps
    })
  }

  $(function () {
    pjax_valine();
  });
</script>




  
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.5/lib/darkmode-js.min.js" aysc></script>

<script type="text/javascript">
function getClientHeight(){
  var clientHeight=0;
  if(document.body.clientHeight&&document.documentElement.clientHeight){
  var clientHeight = (document.body.clientHeight<document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }else{
  var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
  }
  return clientHeight;
}
function supportCss3(style) {
  var prefix = ['webkit', 'Moz', 'ms', 'o'],
  i,
  humpString = [],
  htmlStyle = document.documentElement.style,
  _toHumb = function (string) {
  return string.replace(/-(\w)/g, function ($0, $1) {
  return $1.toUpperCase();
  });
  };
  for (i in prefix)
  humpString.push(_toHumb(prefix[i] + '-' + style));
  humpString.push(_toHumb(style));
  for (i in humpString)
  if (humpString[i] in htmlStyle) return true;
  return false;
};
//配置信息
var options = {
  bottom: '60px',
  right: 'unset',
  left: '1400px',
  time: '0s',
  mixColor: '#f4f4f4',
  backgroundColor: '#f4f4f4',
  buttonColorDark: '#333',
  buttonColorLight: '#ddd',
  saveInCookies: true,
  label: '',
  autoMatchOsTheme: true
};
// 卡片兼容处理 mix-blend-mode 与 effect: [blur] 冲突

function pjax_darkmodejs(){
  
  if(!supportCss3('mix-blend-mode'))return;
  var checkExist2 = setInterval(function() {
     if (typeof jQuery == 'undefined'){return;}
     clearInterval(checkExist2);
     var TopFlag=getClientHeight();
    $(window).scroll(function(){
      var top = $(document).scrollTop();
      if(top > TopFlag) {
        $(".darkmode-layer").css("mix-blend-mode","normal");
        $(".darkmode-layer").css("background-color","#222");
      }else{
        $(".darkmode-layer").css("mix-blend-mode","difference");
        $(".darkmode-layer").css("background-color","");
      }
    })
  }, 100);
  
}
// mix-blend-mode support?
if(supportCss3('mix-blend-mode')){
  window.darkmode = new Darkmode(options);
  
  window.darkmode.showWidget();
  
  pjax_darkmodejs();
}
////////////////Development///////////////////////
//////////////darkmode模式切换////////////////////
//window.darkmode.toggle();                     //
//////////////darkmode模式判断////////////////////
//console.log(window.darkmode.isActivated())    //
//////////////////////////////////////////////////
</script>





  
<script src="/blog/js/app.js"></script>




  
    
<script src="/blog/js/search.js"></script>

  


<!-- optional -->

  <script>
const SearchServiceimagePath="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@master/img/";
const ROOT =  ("/blog/" || "/").endsWith('/') ? ("/blog/" || "/") : ("/blog//" || "/" );
(function ($) {
  
    customSearch = new HexoSearch({
      imagePath: SearchServiceimagePath
    });
  
})(jQuery);

</script>





  
<script src="https://cdn.jsdelivr.net/npm/node-waves@0.7.6/dist/waves.min.js"></script>

  <script type="text/javascript">
    $(function () {
      Waves.attach('.flat-btn', ['waves-button']);
      Waves.attach('.float-btn', ['waves-button', 'waves-float']);
      Waves.attach('.float-btn-light', ['waves-button', 'waves-float', 'waves-light']);
      Waves.attach('.flat-box', ['waves-block']);
      Waves.attach('.float-box', ['waves-block', 'waves-float']);
      Waves.attach('.waves-image');
      Waves.init();
    });
  </script>



  
<script src="https://cdn.jsdelivr.net/gh/volantis-x/cdn-volantis@2/js/comment_typing.js"></script>




  
    
<script src="https://cdn.jsdelivr.net/gh/highlightjs/cdn-release@9.18.1/build/highlight.min.js"></script>

    <script>hljs.initHighlightingOnLoad();</script>
  



  <script defer>

  const LCCounter = {
    app_id: 'u9j57bwJod4EDmXWdxrwuqQT-MdYXbMMI',
    app_key: 'jfHtEKVE24j0IVCGHbvuFClp',
    custom_api_server: '',

    // 查询存储的记录
    getRecord(Counter, url, title) {
      return new Promise(function (resolve, reject) {
        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({url})))
          .then(resp => resp.json())
          .then(({results, code, error}) => {
            if (code === 401) {
              throw error;
            }
            if (results && results.length > 0) {
              var record = results[0];
              resolve(record);
            } else {
              Counter('post', '/classes/Counter', {url, title: title, times: 0})
                .then(resp => resp.json())
                .then((record, error) => {
                  if (error) {
                    throw error;
                  }
                  resolve(record);
                }).catch(error => {
                console.error('Failed to create', error);
                reject(error);
              });
            }
          }).catch((error) => {
          console.error('LeanCloud Counter Error:', error);
          reject(error);
        });
      })
    },

    // 发起自增请求
    increment(Counter, incrArr) {
      return new Promise(function (resolve, reject) {
        Counter('post', '/batch', {
          "requests": incrArr
        }).then((res) => {
          res = res.json();
          if (res.error) {
            throw res.error;
          }
          resolve(res);
        }).catch((error) => {
          console.error('Failed to save visitor count', error);
          reject(error);
        });
      });
    },

    // 构建自增请求体
    buildIncrement(objectId) {
      return {
        "method": "PUT",
        "path": `/1.1/classes/Counter/${ objectId }`,
        "body": {
          "times": {
            '__op': 'Increment',
            'amount': 1
          }
        }
      }
    },

    // 校验是否为有效的 UV
    validUV() {
      var key = 'LeanCloudUVTimestamp';
      var flag = localStorage.getItem(key);
      if (flag) {
        // 距离标记小于 24 小时则不计为 UV
        if (new Date().getTime() - parseInt(flag) <= 86400000) {
          return false;
        }
      }
      localStorage.setItem(key, new Date().getTime().toString());
      return true;
    },

    addCount(Counter) {
      var enableIncr = '' === 'true' && window.location.hostname !== 'localhost';
      enableIncr = true;
      var getterArr = [];
      var incrArr = [];
      // 请求 PV 并自增
      var pvCtn = document.querySelector('#lc-sv');
      if (pvCtn || enableIncr) {
        var pvGetter = this.getRecord(Counter, 'https://hardydragon.gitee.io/blog' + '/#lc-sv', 'Visits').then((record) => {
          incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-sv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + 1;
              if (pvCtn) {
                pvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(pvGetter);
      }

      // 请求 UV 并自增
      var uvCtn = document.querySelector('#lc-uv');
      if (uvCtn || enableIncr) {
        var uvGetter = this.getRecord(Counter, 'https://hardydragon.gitee.io/blog' + '/#lc-uv', 'Visitors').then((record) => {
          var vuv = this.validUV();
          vuv && incrArr.push(this.buildIncrement(record.objectId))
          var eles = document.querySelectorAll('#lc-uv #number');
          if (eles.length > 0) {
            eles.forEach((el,index,array)=>{
              el.innerText = record.times + (vuv ? 1 : 0);
              if (uvCtn) {
                uvCtn.style.display = 'inline';
              }
            })
          }
        });
        getterArr.push(uvGetter);
      }

      // 请求文章的浏览数，如果是当前页面就自增
      var allPV = document.querySelectorAll('#lc-pv');
      if (allPV.length > 0 || enableIncr) {
        for (i = 0; i < allPV.length; i++) {
          let pv = allPV[i];
          let title = pv.getAttribute('data-title');
          var url = 'https://hardydragon.gitee.io/blog' + pv.getAttribute('data-path');
          if (url) {
            var viewGetter = this.getRecord(Counter, url, title).then((record) => {
              // 是当前页面就自增
              let curPath = window.location.pathname;
              if (curPath.includes('index.html')) {
                curPath = curPath.substring(0, curPath.lastIndexOf('index.html'));
              }
              if (pv.getAttribute('data-path') == curPath) {
                incrArr.push(this.buildIncrement(record.objectId));
              }
              if (pv) {
                var ele = pv.querySelector('#lc-pv #number');
                if (ele) {
                  if (pv.getAttribute('data-path') == curPath) {
                    ele.innerText = (record.times || 0) + 1;
                  } else {
                    ele.innerText = record.times || 0;
                  }
                  pv.style.display = 'inline';
                }
              }
            });
            getterArr.push(viewGetter);
          }
        }
      }

      // 如果启动计数自增，批量发起自增请求
      if (enableIncr) {
        Promise.all(getterArr).then(() => {
          incrArr.length > 0 && this.increment(Counter, incrArr);
        })
      }

    },


    fetchData(api_server) {
      var Counter = (method, url, data) => {
        return fetch(`${ api_server }/1.1${ url }`, {
          method,
          headers: {
            'X-LC-Id': this.app_id,
            'X-LC-Key': this.app_key,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(data)
        });
      };
      this.addCount(Counter);
    },

    refreshCounter() {
      var api_server = this.app_id.slice(-9) !== '-MdYXbMMI' ? this.custom_api_server : `https://${ this.app_id.slice(0, 8).toLowerCase() }.api.lncldglobal.com`;
      if (api_server) {
        this.fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + this.app_id)
          .then(resp => resp.json())
          .then(({api_server}) => {
            this.fetchData('https://' + api_server);
          });
      }
    }

  };

  LCCounter.refreshCounter();

  document.addEventListener('pjax:complete', function () {
    LCCounter.refreshCounter();
  });
</script>



<!-- more -->

  
  <script></script>




    
      


<script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.min.js"></script>

<!-- 样式位于：source/css/_third-party/pjaxanimate.styl -->

<div class="pjax-animate">
  
    <script src="https://cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js"></script>
    <div id="loading-bar-wrapper"><script>NProgress.configure({parent:"#loading-bar-wrapper",trickleSpeed: 100})</script></div>
    <script>
      window.ShowLoading = function() {
        NProgress.start();
      };
      window.HideLoading = function() {
        NProgress.done();
      }
    </script>
  
</div>

<script>
    var pjax;
    document.addEventListener('DOMContentLoaded', function () {
      pjax = new Pjax({
        elements: 'a[href]:not([href^="#"]):not([href="javascript:void(0)"]):not([pjax-fancybox])',
        selectors: [
          "title",
          "#pjax-container",
          "#pjax-header-nav-list"
        ],
        cacheBust: false,   // url 地址追加时间戳，用以避免浏览器缓存
        timeout: 5000
      });
    });

    document.addEventListener('pjax:send', function (e) {
      window.stop(); // 相当于点击了浏览器的停止按钮

      try {
        var currentUrl = window.location.pathname;
        var targetUrl = e.triggerElement.href;
        var banUrl = [""];
        if (banUrl[0] != "") {
          banUrl.forEach(item => {
            if(currentUrl.indexOf(item) != -1 || targetUrl.indexOf(item) != -1) {
              window.location.href = targetUrl;
            }
          });
        }
      } catch (error) {}

      window.subData = null; // 移除标题（用于一二级导航栏切换处）
      if (typeof $.fancybox != "undefined") {
        $.fancybox.close();    // 关闭弹窗
      }
      $('.l_header .switcher .s-search').removeClass('active'); // 关闭移动端激活的搜索框
      $('.l_header').removeClass('z_search-open'); // 关闭移动端激活的搜索框
      $('.wrapper').removeClass('sub'); // 跳转页面时关闭二级导航

      // 解绑事件 避免重复监听
      $('.s-top').unbind('click');
      $('.menu a').unbind('click');
      $(window).unbind('resize');
      $(window).unbind('scroll');
      $(document).unbind('scroll');
      $(document).unbind('click');
      $('body').unbind('click');
      window.ShowLoading();
    });

    document.addEventListener('pjax:complete', function () {
      // 关于百度统计对 SPA 页面的处理：
      // 方案一：百度统计>管理>单页应用设置中，打开开启按钮即可对SPA进行统计。 https://tongji.baidu.com/web/help/article?id=324
      // 方案二：取消注释下列代码。 https://tongji.baidu.com/web/help/article?id=235
      // 

      // 关于谷歌统计对 SPA 页面的处理：
      // 当应用以动态方式加载内容并更新地址栏中的网址时，也应该更新通过 gtag.js 存储的网页网址。
      // https://developers.google.cn/analytics/devguides/collection/gtagjs/single-page-applications?hl=zh-cn
      

      $('.nav-main').find('.list-v').not('.menu-phone').removeAttr("style",""); // 移除小尾巴的移除
      $('.menu-phone.list-v').removeAttr("style",""); // 移除小尾巴的移除
      $('script[data-pjax], .pjax-reload script').each(function () {
        $(this).parent().append($(this).remove());
      });
      try{
          if (typeof $.fancybox == "undefined") {
            SCload_fancybox();
          } else {
            pjax_fancybox();
          }
        
          
          if ('.cover-backstretch') {
            $('.cover-backstretch').backstretch("resize");
            if($('.cover-wrapper').is(':hidden')){
              $('.cover-backstretch').backstretch("pause");
            }else{
              $('.cover-backstretch').backstretch("next");
            }
          } else {
            $.backstretch("resize");
            if($('.cover-wrapper').is(':hidden')){
              $.backstretch("pause");
            }else{
              $.backstretch("next");
            }
          }
        
        
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightBlock(block);
        });
        
        
          pjax_scrollrebeal();
        
        
        
          pjax_initCopyCode();
        
        
          pjax_valine();
        
        
        
        
        
          pjax_darkmodejs();
        
      } catch (e) {
        console.log(e);
      }
      window.HideLoading();
    });

    document.addEventListener('pjax:error', function (e) {
      window.HideLoading();
      window.location.href = e.triggerElement.href;
    });
</script>

    
  </div>
</body>
</html>
